let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_COMBINED_NOTIFICATIONS";
const ohana_instance = new ohana(tableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

router.get("/", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '获取列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /* #swagger.parameters['TYPE'] = {
        description: "会员升级、新闻、PO、AS、TA、TE、FI",
        required: false,
      } */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
    }

    let payload = {};
    if (!user.admin) {
        payload.USER_ID = user.user_id;
    }
    let { TYPE } = req.query;
    if (TYPE) {
        payload.TYPE = TYPE;
    }

    getData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/count", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '获得发布条目数量'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);
    if (!user.authCheck) {
        res.sendStatus(403);
    }
    const payload = {
        USER_ID: user.user_id,
    };
    countDataList(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.get("/getByDay", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '获取当天列表'
    // #swagger.description = '需要JWT Token'
    /* #swagger.parameters['TODAY'] = {
        description: "格式为 2021-10-24",
        required: true,
      } */
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const user = checkAuth(req.user, constants.BASICAUTH);

    if (!user.authCheck) {
        res.sendStatus(403);
        return;
    }

    let payload = {};
    if (!user.admin) {
        payload.USER_ID = user.user_id;
    }
    let { TODAY } = req.query;
    if (TODAY) {
        payload.TODAY = TODAY;
    } else {
        res.status(400).send({ message: "参数错误 需要TODAY" });
        return;
    }

    getTodayData(payload)
        .then((result) => {
            res.send(result);
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getTodayData(payload) {
    let result = [];
    result = await ohana_instance.raw(
        "select * from " +
        tableName +
        " where (USER_ID = '" +
        payload.USER_ID +
        "' or USER_ID = 'all') and START_DATE <= '" +
        payload.TODAY +
        "' and END_DATE >= '" +
        payload.TODAY +
        "'"
    );
    return result;
}

async function countDataList(payload) {
    let result = [];
    let typeList = [
        "提醒",
        "会员升级",
        "每日任务",
        "成就勋章",
        "PO",
        "AS",
        "TA",
        "TE",
        "FI",
        "新闻",
        "外链新闻",
    ];
    for (let i in typeList) {
        let countResult = 0;
        countResult = await ohana_instance.count({
            USER_ID: payload.USER_ID,
            TYPE: typeList[i],
        });
        result.push({
            TYPE: typeList[i],
            count: countResult[0]["COUNT(*)"],
        });
    }
    return result;
}

router.post("/", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '插入列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/combined_add"
                          }  
                      },
                  }
          } */
    let { data } = req.body;
    insertData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.put("/", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '更新列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/combined_update"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    updateData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

router.delete("/", function (req, res, next) {
    // #swagger.tags = ['发布']
    // #swagger.summary = '删除列表'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    /*	#swagger.requestBody = {
                  required: true,
                  content: {
                      "application/json": {
                          schema: {
                              $ref: "#/definitions/combined_delete"
                          }  
                      },
                  }
          } */
    const { data } = req.body;
    deleteData(data)
        .then((result) => {
            if (result == 1) {
                res.sendStatus(200);
            } else {
                res.sendStatus(500);
            }
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});

async function getData(condition) {
    let result = [];
    if (!condition) {
        result = "请登录";
    } else {
        result = await ohana_instance.find(condition);
    }
    return result;
}

async function insertData(data) {
    data.COMBINED_NOTIFICATION_ID = uunewid.v4();
    let result = await ohana_instance.insert(data);
    return result;
}

async function updateData(data) {
    let result = await ohana_instance.update(
        {
            COMBINED_NOTIFICATION_ID: data.COMBINED_NOTIFICATION_ID,
        },
        data
    );
    return result;
}

async function deleteData(data) {
    let result = await ohana_instance.raw(
        'delete from "' +
        tableName +
        "\" where COMBINED_NOTIFICATION_ID = '" +
        data.COMBINED_NOTIFICATION_ID +
        "'"
    );
    return result;
}

module.exports = router;
